package com.redrose.flutterdemo.camera;

import android.content.Context;
import android.hardware.Camera;
import android.support.design.widget.Snackbar;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.redrose.flutterdemo.utils.BitmapCallBack;
import com.redrose.flutterdemo.utils.LogUtils;
import com.redrose.flutterdemo.utils.ToastUtil;

/**
 * Desc:
 * Author: RedRose
 * Date: 2019/3/20
 * Email: yinsxi@163.com
 */

public class Preview extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback, Camera.PictureCallback {

    private Camera mCamera;
    private BitmapCallBack mBitmapCallback;
    private static final String TAG = Preview.class.getSimpleName();

    public Preview(Context context) {
        this(context, null);
    }

    public Preview(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public Preview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mCamera = CameraUtil.getInstance().openCamera();
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        LogUtils.e(TAG, " --surfaceCreated--");
        //这里必须要这样处理，比如锁屏，回到桌面，再次回到相机的时候，surfaceCreated 会重新执行
        //所以，要加个标识，判断是否被释放过资源
        if (CameraUtil.getInstance().getIsRelease()) {
            mCamera = CameraUtil.getInstance().openCamera();
        }
        mCamera.setPreviewCallback(this);
        CameraUtil.getInstance().doStartPreview(holder);

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        LogUtils.e(TAG, " --surfaceChanged--");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        LogUtils.e(TAG, " --surfaceDestroyed--");
        //每次 执行surfaceDestroyed，都要销毁，释放camera
        CameraUtil.getInstance().releaseCamera();
    }

    /**
     * 预览回调
     */
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {

    }

    /**
     * 拍摄成功后回调
     */
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        if (mBitmapCallback != null) {
            mBitmapCallback.backByte(data);
        }
        camera.startPreview();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        /**
         * 触摸聚焦
         */
        mCamera.autoFocus(new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                if (success) {
                    ToastUtil.show(getContext(), "聚焦成功");
//                    showSnackbar("聚焦成功");
                    camera.cancelAutoFocus();
                }
            }
        });
        return super.onTouchEvent(event);
    }
    protected void showSnackbar(String str) {
        Snackbar.make(this, str, Snackbar.LENGTH_LONG).show();
    }
    public void takePhoto() {
        mCamera.autoFocus(new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                //设置聚焦成功后再拍照，其实可以不用。看需求吧，可以直接调用takePicture（）
                //有些手机会聚焦失败，也就是success是false
                if (success) {
                    camera.cancelAutoFocus();
                    mCamera.takePicture(null, null, Preview.this);
                }
            }
        });
    }

    /**
     * 设置回调到Activity吧
     */
    public void setBitmapCallback(BitmapCallBack callback) {
        this.mBitmapCallback = callback;
    }
}
